package com.it.flowable.controller;

import com.it.flowable.dto.*;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.HistoryService;
import org.flowable.engine.IdentityService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.history.HistoricProcessInstanceQuery;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 开启流程
 * <br/>
 * 获取所有流程, 历史的,进行中的
 * 获取流程详情, 环境变量, 当前审批节点, BPM图
 *
 */
@Slf4j
@RestController
@RequestMapping("/api/process/exec")
public class ProcessTaskController {

    @Resource
    private TaskService taskService;

    /**
     * 查询所有流程
     */
    @GetMapping("/getPage")
    public List<TaskInfoVo> getPage(TaskQo taskQo) {
        TaskQuery taskQuery = taskService.createTaskQuery();
        if (taskQo.getAssign() != null && !taskQo.getAssign().isEmpty()) {
            taskQuery.taskAssignee(taskQo.getAssign());
        }
        if (taskQo.getProcessDefinitionKey() != null && !taskQo.getProcessDefinitionKey().isEmpty()) {
            taskQuery.processDefinitionKey(taskQo.getProcessDefinitionKey());
        }
        if (taskQo.getProcessInstanceId() != null && !taskQo.getProcessInstanceId().isEmpty()) {
            taskQuery.processDefinitionKey(taskQo.getProcessInstanceId());
        }

        List<Task> tasks = taskQuery
                .includeProcessVariables()  // 包含流程变量
                .includeTaskLocalVariables() // 包含任务本地变量
                .list();
        // 转换成VO
        // forms
        List<TaskInfoVo> taskInfoVos = tasks.stream()
                .map(task -> {
                    Map<String, Object> variables = taskService.getVariables(task.getId());

                    return new TaskInfoVo(task, variables);
                })
                .collect(Collectors.toList());
        return taskInfoVos;
    }
}